"""
  Created by Amor on 2018-08-26
"""
from rest_framework import serializers

from VueShop.settings import PRIVATE_KEY_PATH, ALI_PUB_KEY_PATH, APP_ID
from utils.generate import get_order_sn
from utils.alipay import AliPay
from goods.models import Goods
from goods.serializers import GoodsSerializer
from .models import ShoppingCart, OrderInfo, OrderGoods

__author__ = '骆杨'


class ShopCartDetailSerializer(serializers.ModelSerializer):

    goods = GoodsSerializer(many=False)

    class Meta:
        model = ShoppingCart
        fields = '__all__'


class ShopCartSerializer(serializers.Serializer):
    """
    购物车
    """
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    nums = serializers.IntegerField(required=True, min_value=1, label='数量',
                                    error_messages={
                                        'min_value': '商品数量不能小于1',
                                        'required': '请选择购买数量'
                                    })
    goods = serializers.PrimaryKeyRelatedField(required=True, label='商品', queryset=Goods.objects.all())

    def update(self, instance, validated_data):
        instance.nums = validated_data['nums']
        instance.save()
        return instance

    def create(self, validated_data):
        user = self.context['request'].user
        nums = validated_data['nums']
        goods = validated_data['goods']

        existed = ShoppingCart.objects.filter(user=user, goods=goods)

        if existed:
            existed = existed[0]
            existed.nums += nums
            existed.save()
        else:
            existed = ShoppingCart.objects.create(**validated_data)

        return existed


class OrderSerializer(serializers.ModelSerializer):

    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    order_sn = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    pay_status = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    alipay_url = serializers.SerializerMethodField(read_only=True)

    def get_alipay_url(self, obj):
        alipay = AliPay(
            app_id=APP_ID,
            app_notify_url='http://47.98.207.4:8080/alipay/return/',
            app_private_key_path=PRIVATE_KEY_PATH,
            alipay_public_key_path=ALI_PUB_KEY_PATH,
            debug=True,  # 默认False,
            return_url='http://47.98.207.4:8080/alipay/return/'
        )

        url = alipay.direct_pay(
            subject=obj.order_sn,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_mount,
            return_url='http://47.98.207.4:8080/alipay/return/'
        )
        return 'https://openapi.alipaydev.com/gateway.do?{data}'.format(data=url)

    def validate(self, attrs):
        attrs['order_sn'] = get_order_sn(self.context['request'].user.id)
        return attrs

    class Meta:
        model = OrderInfo
        fields = '__all__'


class OrderGoodsSerializer(serializers.ModelSerializer):

    goods = GoodsSerializer(many=False)

    class Meta:
        model = OrderGoods
        fields = '__all__'


class OrderDetailSerializer(OrderSerializer):
    goods = OrderGoodsSerializer(many=True)
